//依赖于axios对私有ajax进行修改
import Qs from 'qs'
import axios from 'axios'
import {errorPrompt} from 'util/util'

export function fetch(options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      //baseURL: process.env.BASE_API,
      timeout: 2000,
      //headers: { 'X-Ivanka-Token': store.getters.token }
    });
    instance(options)
        .then(response => {
          const res = response.data;
          if (res.errorCode !== '100') {
            //console.log(options); // for debug
            errorPrompt(res.message)
            // 50014:Token 过期了 50012:其他客户端登录了 50008:非法的token
            if (res.code === 50008 || res.code === 50014 || res.code === 50012) {
              errorPrompt(res.message)
              // router.push({path: '/'})
              // TODO
              // store.dispatch('FedLogOut').then(() => {
              //   router.push({ path: '/login' })
              // });
            }
            reject(res);
          }
          resolve(res);
        })
        .catch(error => {
          errorPrompt('发生异常错误,请刷新页面重试,或联系程序员')
          console.log(error); // for debug
          reject(error);
        });
  });
}

// export function fetch(options) {
//   return new Promise((resolve, reject) => {
//     const instance = axios.create({
//       timeout: 2000 // 超时
//     });
//     instance(options)
//         .then(response => {
//           const res = response.data;
//           resolve(res);
//         })
//         .catch(error => {
//           errorPrompt(error)
//           console.log(error); // for debug
//           reject(error);
//         });
//   });
// }

export function commonBizHeader(xhr) {
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  let params = {}
  params['ua'] = UA
  params['cv'] = '20161230'
  params['ws'] = window.screen.height + '*' + window.screen.width
  if (window.localStorage.getItem('token')) {
    params['token'] = window.localStorage.getItem('token') // 用户令牌
  }
  params['app'] = 'aplus'
  let UUID = window.localStorage.getItem('aplusUUID')
  if (!UUID) {
    UUID = getUUID()
    window.localStorage.setItem('aplusUUID', UUID)
  }
  params['pkey'] = UUID
  xhr.setRequestHeader('tracecode', window.encodeURIComponent(JSON.stringify(params)))
}